# coding=utf-8

import tornado.ioloop
import tornado.options
import tornado.web
from tornado import gen

from adsl_info import ADSLInfo
from common import log

tornado.options.parse_command_line()

# 拨号信息
adsl_info = ADSLInfo(log)


# 获取动态代理
class GetProxy(tornado.web.RequestHandler):
    def data_received(self, chunk):
        pass

    @gen.coroutine
    def get(self, host):
        proxy = adsl_info.get_proxy(str(host))
        log.info("获取代理站点: host = {} proxy = {}".format(host, proxy))
        self.write(proxy)


# 反馈动态代理 目前没考虑清楚可能不会进行操作
class BadProxy(tornado.web.RequestHandler):
    def data_received(self, chunk):
        pass

    @gen.coroutine
    def get(self, host, ip):
        # log.info(host)
        # log.info(ip)
        self.write('success')


def make_app():
    return tornado.web.Application([
        (r"/proxy/(.*?)", GetProxy),
        (r"/bad_proxy/(.*?)/(.*?)", BadProxy),
    ], autoreload=True)


if __name__ == "__main__":
    log.info("启动动态代理服务...")
    try:
        app = make_app()
        app.listen(9300)
        tornado.ioloop.IOLoop.current().start()
    except Exception as e:
        log.error("启动动态代理服务失败...")
        log.exception(e)
